import React, { useEffect, useState, useMemo} from 'react'
import { IndexBar, List,SearchBar} from 'antd-mobile'
import {hotCities,cityList} from '../../../public/cities.json'
import './index.css'
// import axios from 'axios'
import axios from '../../utils/request'
import style from './index.module.css'
import { useLocation,useNavigate } from 'react-router-dom'
// 3、封装城市选择组件，实现出发城市和目的地城市的选择
function City() {
    const location = useLocation()
    const navigate = useNavigate()
    const [hotArr,setHotArr] = useState(hotCities)
    const [cityItem,setCityItem]=useState('')
    // 4、城市选择：定位当前位置根据地图api获取当前城市
    const handleAddress = async()=>{
      // 4、使用 useMemo 减少渲染次数，提升性能
      console.log('4、使用 useMemo 减少渲染次数，提升性能')
      let res=await axios.get("/city/v3/ip",{
          params:{
              key:'b2fe83f731ba6eae0012f0c9023e143b'
          }
      })
      setCityItem(res.data.city)
  }

    const handleCity=(name)=>{
      const cityitem=location.state.value
      if(cityitem=='left'){
        localStorage.setItem('cityLeft',name)
      }else{
        localStorage.setItem('cityRight',name)

      }
      navigate(`/hot?city=${name}&value=${cityitem}`)
    }

    useEffect(()=>{
        handleAddress()
        console.log(hotArr)
    })
    useMemo(()=>{
        handleAddress()
    },[])
  return (
    <div style={{paddingRight:'20px'}}>
        <div style={{ height: window.innerHeight }}>
        <SearchBar placeholder='请输入内容' />
            <div className={style.city_ip}>
                <p>当前(国家、地区或城市)</p>
                <span className={style.city_span}>{cityItem}</span>
            </div>
            <div className={style.city_box}>
                <p>热门城市</p>
                <div className={style.city_hot}>
              
                  {
                    hotArr.map((item,index)=>{
                      return <div key={index} className={style.city_div} onClick={()=>handleCity(item.name)}>
                        {item.name}
                      </div>
                    })
                  }
               
                </div>
            </div>
            {/* 3、实现热门城市的渲染 */}
      <IndexBar>
        {cityList.map(group => {
          const { title, citys } = group
          return (
            // 3、最右边侧边导航渲染，点击右侧大写首字母，页面滚动到对应的城市列表
            <IndexBar.Panel
              index={title}
              title={title}
              key={title}
            >
              {/* 4、渲染侧边字母，数据不能写死（从总数据中筛选），字母不能出现重复 */}
              <List>
                {citys.map((item, index) => (
                  <List.Item key={index} onClick={()=>handleCity(item.name)}>{item.name}</List.Item>
                ))}
              </List>
            </IndexBar.Panel>
          )
        })}
      </IndexBar>
    </div>
    </div>
  )
}

export default City
